package com.besall.allbase.view.activity.chipstoollevel4.protocol.Settings.storagemanager;

import static com.bes.bessdk.BesSdkConstants.BES_CONNECT_ERROR;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.BIKEWATCH_DELETE_ROUTEBOOKS_FILES;
import static com.besall.allbase.common.utils.ActivityUtils.showToast;

import java.util.List;

import com.bes.bessdk.service.base.BBServiceListener;
import com.bes.bessdk.service.base.BesServiceListener;
import com.bes.sdk.device.HmDevice;
import com.bes.sdk.message.Constants;
import com.bes.sdk.utils.SettingsJsonUtils;
import com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants;
import com.besall.allbase.common.utils.FileUtils;
import com.besall.allbase.view.activity.chipstoollevel4.protocol.ProtocolPresenter;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.PopupMenu;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.device.sgdevcie.setting.fragment.adapter.RouteBookManageAdapter;
import bb.lanxing.devicelist.XZDeviceListActivity;
import bb.lanxing.lib.devices.sgsettingentity.routebook.Route;
import bb.lanxing.lib.devices.sgsettingentity.routebook.Routebooks;
import bb.lanxing.util.RouteBookUtil;
import bb.lanxing.view.dialog.CircularProgressDialog;

public final class LaxingRouteBookManagerFragment extends Fragment
        implements View.OnClickListener, BesServiceListener, BBServiceListener {

    private static final String TAG = "LaxingRouteBookManagerFragment";
    static ProtocolPresenter protocolPresenter = null;
    RecyclerView recyclerView;
    RadioGroup radioGroup;
    // RadioButton radioAll;
    CheckBox selectAll;
    TextView tvDelete;
    View llBottomPannel;
    Routebooks routebooks = null;
    CircularProgressDialog circularProgressDialog;
    private boolean isEdit;
    private Menu menu;
    private RouteBookManageAdapter routeBookAdapter;
    private Activity mActivity;
    private String deviceModel = null;
    private String deviceSn = null;

    public static LaxingRouteBookManagerFragment newInstance() {
        return new LaxingRouteBookManagerFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: Use the ViewModel
        deviceModel = SettingsJsonUtils.getDeviceModel(getContext());
        deviceSn = SettingsJsonUtils.getSn(getContext());
        protocolPresenter = ProtocolPresenter.getInstance();
        protocolPresenter.setProtocolServiceListener(this);
        protocolPresenter.setProtocolBBServiceListener(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.lanxing_routebook_manager, container, false);// storage_manager_fragment
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        routeBookAdapter = new RouteBookManageAdapter(this);
        routeBookAdapter.setOnItemLongClickListener((baseQuickAdapter, view, i) -> {
            PopupMenu popupMenu = new PopupMenu(requireContext(), view, Gravity.BOTTOM);
            popupMenu.inflate(R.menu.menu_delete);
            popupMenu.setOnMenuItemClickListener(menuItem -> {
                routeBookAdapter.clearChecked();
                if (menuItem.getItemId() == R.id.delete) {
                    routeBookAdapter.getItem(i).setChecked(true);
                    deleteChecked();
                }
                return true;
            });
            popupMenu.show();
            return true;

        });
        initView();
        getRouteBooksJsonFileFromBesClient();

        /*
         * parseRouteBooksJson(); if(routebooks != null){ routeBookAdapter.setList(routebooks.getRoutes()); }
         */
    }

    // send cmd to device get the routebook.json file
    private void getRouteBooksJsonFileFromBesClient() {
        if (protocolPresenter == null || deviceModel == null || deviceSn == null) {
            Log.d(TAG, " get routebook.json params is null,return.");
            return;
        }
        showLoadingDialog();
        Log.d(TAG, " begin send cmd get routebook.json.");
        protocolPresenter.getBikeWatchDataFromBesClient(ProtocolConstants.BIKEWATCH_GET_ROUTE_BOOKS_INFO, deviceModel,
                deviceSn);
    }

    /* storage/emulated/0/Android/data/bb.lanxing/files/lanxing/Lanxing/123456/Routebooks/routebooks.json */
    private void parseRouteBooksJson() {

        String fileDirStr = FileUtils.checkExternalDirectoryPathExist(true, deviceModel, deviceSn,
                SettingsJsonUtils.ROUTE_BOOKS_FOLDER, SettingsJsonUtils.ROUTE_BOOKS_JSON);
        Log.d(TAG, " the file dir: " + fileDirStr); // SettingsJsonUtils.ROUTE_BOOKS_JSON
        if (fileDirStr != null) {
            routebooks = FileUtils.createRouteBooksFromFile(fileDirStr);
            // Log.d(TAG," routebooks str: " + routebooks.toString());
            runOnUIThread(() -> {
                dismissLoadingDialog();
                if (routebooks != null && !routebooks.routes.isEmpty()) {
                    Log.d(TAG, " the route books infor: " + routebooks.toString());
                    if (!selectAll.isEnabled()) {
                        selectAll.setEnabled(true);
                    }
                    if (!tvDelete.isEnabled()) {
                        tvDelete.setEnabled(true);
                    }
                    routeBookAdapter.setList(routebooks.routes);
                } else {
                    Log.d(TAG, " the route books set empty view: ");
                    routeBookAdapter.setList(null);
                    routeBookAdapter.setEmptyView(R.layout.route_empty_view);
                    selectAll.setEnabled(false);
                    tvDelete.setEnabled(false);
                    // recyclerView.requestLayout();

                    // recyclerView.setAdapter(routeBookAdapter);
                    /*
                     * routeBookAdapter.notifyDataSetChanged(); recyclerView.invalidate();
                     */
                }
            });

        }

    }
    /*
     * public XossSGDeviceRouteBookManagerFragment() { super(R.layout.fragment_xoss_s_g_device_routebook_manager); final
     * XossDeviceRouteBookManageAdapter routeBookAdapter = new XossDeviceRouteBookManageAdapter();
     * routeBookAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
     *
     * @Override public final boolean onItemLongClick(BaseQuickAdapter baseQuickAdapter, View view, int i) { PopupMenu
     * popupMenu = new PopupMenu(requireContext(), view, Gravity.BOTTOM); popupMenu.inflate(R.menu.menu_delete);
     * popupMenu.setOnMenuItemClickListener(menuItem -> { routeBookAdapter.clearChecked(); if (menuItem.getItemId() ==
     * R.id.delete) { routeBookAdapter.getItem(i).setChecked(true); deleteChecked(); } return true; });
     * popupMenu.show(); return true;
     *
     * } }); this.xossDeviceRouteBookManageAdapter = routeBookAdapter; //XossSGDeviceRouteBookManagerFragment
     * xossSGDeviceRouteBookManagerFragment = this; //TODO:hu // this.xossSGDeviceViewModel$delegate =
     * FragmentViewModelLazyKt.createViewModelLazy(xossSGDeviceRouteBookManagerFragment,
     * Reflection.getOrCreateKotlinClass(XossSGDeviceViewModel.class), new
     * VMStoreKt$viewModelWithScope$2(xossSGDeviceRouteBookManagerFragment, "SCOPE_STORAGE_MANAGE"), new
     * VMStoreKt$viewModelWithScope$3(xossSGDeviceRouteBookManagerFragment), null); }
     */

    public void initView() {
        if (mActivity == null) {
            mActivity = requireActivity();
        }
        setHasOptionsMenu(true);
        llBottomPannel = mActivity.findViewById(R.id.ll_bottom_pannel);
        tvDelete = mActivity.findViewById(R.id.routebook_delete);
        tvDelete.setOnClickListener(this);
        radioGroup = mActivity.findViewById(R.id.radio_group);
        // radioAll = mActivity.findViewById(R.id.radio_all);
        selectAll = mActivity.findViewById(R.id.select_all_route_file);
        mActivity.setTitle(R.string.route_book_list_title);
        recyclerView = mActivity.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        DefaultItemAnimator defaultItemAnimator = new DefaultItemAnimator();
        defaultItemAnimator.setSupportsChangeAnimations(false);
        recyclerView.setItemAnimator(defaultItemAnimator);
        recyclerView.setAdapter(routeBookAdapter);
        // add by wangsm
        selectAll.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                routeBookAdapter.checkAll();
            } else {
                if (!routeBookAdapter.unCheckedItemExist()) {
                    routeBookAdapter.clearChecked();
                }
            }
        });

        /*
         * radioGroup.setOnClickListener(new View.OnClickListener() {
         *
         * @Override public void onClick(View v) { Log.d(TAG," radio group click, "); int id = v.getId(); if (id ==
         * R.id.radio_all) { // radioAll.isChecked() if(radioAll.isChecked()){ routeBookAdapter.clearChecked();
         * Log.d(TAG," radio group click, radio all false "); radioAll.setChecked(false); }else {
         * routeBookAdapter.checkAll(); Log.d(TAG," radio group click, radio all true "); radioAll.setChecked(true); } }
         * RadioButton radioButton = v.findViewById(R.id.radio_all); if(radioButton.isChecked()){
         * routeBookAdapter.clearChecked(); radioButton.setChecked(false); }else { routeBookAdapter.checkAll();
         * radioButton.setChecked(true); } } });
         */

        /*
         * radioGroup.setOnCheckedChangeListener((radioAll, i) -> { Log.d(TAG," radio group checked, i: " + i); if (i ==
         * R.id.radio_all) { RadioButton radioButton = radioAll.findViewById(R.id.radio_all);
         * if(radioButton.isChecked()){ Log.d(TAG," radio group radioButton is checked, : " ); //
         * routeBookAdapter.clearChecked(); //radioButton.setChecked(false); }else {
         * Log.d(TAG," radio group radioButton is not checked, : " ); // routeBookAdapter.checkAll(); //
         * radioButton.setChecked(true); } if(routeBookAdapter.isAllChecked()){ // routeBookAdapter.clearChecked();
         * }else{ // routeBookAdapter.checkAll(); }
         *
         * } });
         *
         * radioAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
         *
         * @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
         * Log.d(TAG," the radio all check: " + isChecked); if(isChecked){
         * Log.d(TAG," the radio all checked,is checked"); }else { Log.d(TAG," the radio all checked,is not checked"); }
         * } }); radioAll.setOnClickListener(new View.OnClickListener() {
         *
         * @Override public void onClick(View v) { Log.d(TAG," the radio all click"); if(radioAll.isChecked()){
         * Log.d(TAG," the radio all click,is checked"); // radioAll.setChecked(true); }else {
         * Log.d(TAG," the radio all click,is not checked"); // radioAll.setChecked(false); //
         * radioAll.setChecked(true); } } });
         */
        // tvDelete.setOnClickListener(view -> deleteChecked());
    }

    public void deleteChecked() {
        // TODO:hu
        // getXossSGDeviceViewModel().deleteDeletableList(this.xossDeviceRouteBookManageAdapter.getCheckedItem(), new
        // XossSGDeviceRouteBookManagerFragment$deleteChecked$1(this), new
        // XossSGDeviceRouteBookManagerFragment$deleteChecked$2(this), new
        // XossSGDeviceRouteBookManagerFragment$deleteChecked$3(this));
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        if (!this.isEdit) {
            inflater.inflate(R.menu.menu_edit, menu);
        } else {
            inflater.inflate(R.menu.menu_done, menu);
        }
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        this.menu = menu;
        if (!this.isEdit) {
            List<Route> data = routeBookAdapter.getData();
            if (data.isEmpty()) {
                dismissOptionMenu();
            }
        }
    }

    public final void dismissOptionMenu() {
        Menu menu = this.menu;
        if (menu != null) {
            menu.getItem(0).setVisible(false);
            menu.getItem(0).setEnabled(false);
        }
    }

    public final void showOptionMenu() {
        Menu menu = this.menu;
        if (menu != null) {
            menu.getItem(0).setVisible(true);
            menu.getItem(0).setEnabled(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_item_done) {
            this.isEdit = false;
            requireActivity().invalidateOptionsMenu();
            llBottomPannel.setVisibility(View.GONE);
            routeBookAdapter.setEditMode(false);

        } else if (item.getItemId() == R.id.menu_item_edit) {
            this.isEdit = true;
            requireActivity().invalidateOptionsMenu();
            llBottomPannel.setVisibility(View.VISIBLE);
            radioGroup.clearCheck();
            routeBookAdapter.setEditMode(true);
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.routebook_delete) {
            showLoadingDialog();
            List<String> ridList = routeBookAdapter.getCheckedRouteRidList();
            if (ridList != null && !ridList.isEmpty()) {
                ProtocolPresenter.getInstance().sendBikeWatchDeleteFiles(getContext(), ridList,
                        BIKEWATCH_DELETE_ROUTEBOOKS_FILES);
                RouteBookUtil.deleteRouteBookFiles(ridList);
            }
        }
    }

    public void updateFragmentViews() {
        if (selectAll != null) {
            boolean existUnchecked = routeBookAdapter.unCheckedItemExist();
            if (existUnchecked) {
                selectAll.setChecked(false);
            } else {
                selectAll.setChecked(true);
            }
        }
    }

    public void dismissLoadingDialog() {
        if (circularProgressDialog != null) {
            circularProgressDialog.dismiss();
            circularProgressDialog = null;
        }
    }

    private void showLoadingDialog() {
        if (circularProgressDialog == null) {
            circularProgressDialog = new CircularProgressDialog(getActivity(), true, true, null);
        }
        circularProgressDialog.show(R.string.dialog_loading);
    }

    @Override
    public void onBBSMessage(int msg, String params) {
        Log.d(TAG, " onBBSuccessMessage,msg: " + msg + " params: " + params);
    }

    @Override
    public void onTotaConnectState(boolean state, HmDevice hmDevice) {
        Log.d(TAG, " onTotaConnectState,state: " + state);
    }

    @Override
    public void onErrorMessage(int msg, HmDevice hmDevice) {
        Log.d(TAG, " onErrorMessage,msg: " + msg);
        if (msg == Constants.NO_JSON_FILE_EXIST && routeBookAdapter != null) {
            runOnUIThread(() -> {
                dismissLoadingDialog();
                if (routeBookAdapter != null) {
                    routeBookAdapter.setEmptyView(R.layout.route_empty_view);
                }
                if (selectAll != null) {
                    selectAll.setEnabled(false);
                }
                if (tvDelete != null) {
                    tvDelete.setEnabled(false);
                }
            });
        }
        if (msg == BES_CONNECT_ERROR) {
            runOnUIThread(() -> {
                dismissLoadingDialog();
                showToast(R.string.connect_failed);
            });
        }
    }

    @Override
    public void onStateChangedMessage(int msg, String msgStr, HmDevice hmDevice) {
        Log.d(TAG, " onStateChangedMessage,msg: " + msg + " msgStr: " + msgStr);
        if (msg == BES_CONNECT_ERROR) {
            runOnUIThread(() -> {
                dismissLoadingDialog();
                showToast(msgStr);
            });
            if (isAdded()) {
                Intent intent = new Intent(mActivity, XZDeviceListActivity.class);
                startActivity(intent);
            }

        }
    }

    @Override
    public void onSuccessMessage(int msg, HmDevice hmDevice) {
        Log.d(TAG, " onSuccessMessage,msg: " + msg);
        if (msg == Constants.SAVE_ROUTE_JSON_FILE_SUCCESS) {
            parseRouteBooksJson();
        }
    }

    public void runOnUIThread(Runnable runnable) {
        if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
            runnable.run();
        } else {
            App.getContext().getHandler().post(runnable);
        }
    }

    @Override
    public void onStop() {
        dismissLoadingDialog();
        super.onStop();
    }
}
